package com.zhangfb95.crosschain.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhangfb95.crosschain.infra.exception.BusinessException;
import com.zhangfb95.crosschain.server.infra.data.mapper.UserMapper;
import com.zhangfb95.crosschain.server.infra.model.mapper.entity.User;
import com.zhangfb95.crosschain.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author zhangfubing
 * @since 2023/10/19
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void add(User user) {
        checkUsernameExist(user.getUsername(), null);
        userMapper.insert(user);
    }

    @Override
    public void updateUsername(Long id, String username) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("user not exist");
        }
        checkUsernameExist(username, id);
        user.setUsername(username).setGmtModified(new Date());
        userMapper.updateById(user);
    }

    @Override
    public void updatePassword(Long id, String password) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("user not exist");
        }
        user.setPassword(password).setGmtModified(new Date());
        userMapper.updateById(user);
    }

    @Override
    public void updateSecret(Long id, String secret) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("user not exist");
        }
        user.setSecret(secret).setGmtModified(new Date());
        userMapper.updateById(user);
    }

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    private void checkUsernameExist(String username, Long userId) {
        if (username == null) {
            return;
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null && !user.getId().equals(userId)) {
            throw new BusinessException("username existed");
        }
    }
}
